<?php
class Page{
	private $total;//总信息数
	private $rows;//每页显示数
	private $pageNum;//总页数
	private $start;//开始记录
	private $end;//结束记录
	private $cur;//当前页
	private $url;//当前url
	public function __construct($total,$rows=10){
		$page = isset($_GET['page'])?(int)$_GET['page']:1;
		$this->total = (int)$total;//总信息数
		$this->rows = $rows;//每页信息数量
		$this->pageNum = ceil($this->total/$this->rows);//总页数
		if(!$this->pageNum) $this->pageNum = 1;
		$this->cur = min($this->pageNum,max(1,$page));//当前页
		
		$this->start = $this->rows * ($this->cur-1) + 1;//开始记录

		$this->end = min($this->total,($this->start + $this->rows -1));//结束记录
		
		$this->setUrl();//url设置
		// header("Content-type:text/html;charset=utf-8");
		// echo $this->limit();
	}

	/**
	 * [limit 返回数据库limit查询限制]
	 * @return [string] [limit查询]
	 */
	public function limit(){
		return $this->start.','.$this->end;	
	}

	/**
	 * [setUrl 返回带参数网址，过滤page参数]
	 */
	private function setUrl(){
		$url = $_SERVER['REQUEST_URI'];//获得当前网址
		$urlArr = parse_url($url);//解析网址
		$path = $urlArr['path'];//网址路径
		$query = isset($urlArr['query'])?$urlArr['query']:'';//url参数
		if($query){
			parse_str($query,$qArr);
			unset($qArr['page']);
		}
		
		$this->url = $query?$path . '?' . http_build_query($qArr).'&page=':$path.'?page=';
		
	}
	/**
	 * [first 首页]
	 * @return [type] [description]
	 */
	private function first(){
		return $this->cur > 1?"<a href='".$this->url."1'>首页</a>":'';
	}
	/**
	 * [pre 上一页]
	 * @return [type] [description]
	 */
	private function pre(){
		return $this->cur > 1?"<a href='".$this->url.max(1,($this->cur-1))."'>上一页</a>":'';
	}

	/**
	 * [next 下一页]
	 * @return function [description]
	 */
	private function next(){
		return $this->cur < $this->pageNum?"<a href='".$this->url.min($this->pageNum,($this->cur+1))."'>下一页</a>":'';
	}

	/**
	 * [last 末页]
	 * @return [type] [description]
	 */
	private function last(){
		return $this->cur < $this->pageNum?"<a href='".$this->url.$this->pageNum."'>末页</a>":'';
	}

	/**
	 * [show 显示分页]
	 * @return [string] [分页显示字符串]
	 */
	public function show(){

		$show = $this->first().$this->pre().$this->next().$this->last();
		
		return $show;
	}
}
?>
